package com.bigger.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bigger.constant.ErrorConstant;
import com.bigger.context.BaseContext;
import com.bigger.dto.CreateOrderDTO;
import com.bigger.entity.*;
import com.bigger.exception.OrderException;
import com.bigger.exception.PowerException;
import com.bigger.mapper.*;
import com.bigger.service.OrderService;
import com.bigger.service.ShoppingCarService;
import com.bigger.vo.OrderDetailVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCarService shoppingCarService;

    @Override
    @Transactional//开启事务
    public void createOrder(CreateOrderDTO createOrderDTOList) {
        List<ShoppingCar> shoppingCars = shoppingCarService.get(); //获取本用户购物车中的信息
        User user = userMapper.selectById(BaseContext.getCurrentId()); //通过id获取用户信息
        if (shoppingCars.isEmpty()){ //对购物车进行判空
            throw new OrderException(ErrorConstant.ORDER_IS_EMPTY);
        }
        List<OrderDetail> orderDetails=new ArrayList<>();
        BigDecimal totalPrice=BigDecimal.ZERO;
        for (ShoppingCar shoppingCar : shoppingCars) { //遍历购物车中的物品信息
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCar,orderDetail);
            orderDetail.setId(null);
            orderDetails.add(orderDetail); //将购物车中的信息添加到订单详情列表中
            BigDecimal price = BigDecimal.valueOf(orderDetail.getPrice()); //获取单价
            price=price.multiply(BigDecimal.valueOf(orderDetail.getNumber())); //获取数量并进行总价计算(公式 总价=单价*数量)
            totalPrice=totalPrice.add(price); //进行总价的计算
        }
        if (user.getIsVIP().equals(1)){//如果为会员则打7折
            totalPrice = totalPrice.multiply(new BigDecimal("0.7"));
        }
        LocalDateTime now =LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
        Order order=new Order(
                null,String.valueOf(System.currentTimeMillis()),createOrderDTOList.getAddressId(),
                BaseContext.getCurrentId(),totalPrice.doubleValue(),0L,Order.WAIT_GIVE,"暂未有接单手", now,now
        );
        shoppingCarService.deleteAll(); //清空购物车中的数据
        orderMapper.insert(order); //插入订单信息
        orderDetails.forEach(orderDetail->{
            orderDetail.setOrderId(order.getId()); //遍历对订单详情中的订单id进行赋值
            orderDetailMapper.insert(orderDetail); //插入订单详情信息
        });
    }

    @Override
    public List<Order> get() { //以后需要对此接口进行更改，传参来增加接口查询数据的自由度
        LocalDateTime end = LocalDateTime.now(ZoneId.of("Asia/Shanghai")); //获取现在的时间
        LocalDateTime start = end.minusDays(30); //获取30天前的日期
        QueryWrapper<Order> wrapper=new QueryWrapper<Order>()
                .eq("user_id",BaseContext.getCurrentId())
                .between("create_time",start,end)
                .orderBy(true,false,"create_time");
        List<Order> orders = orderMapper.selectList(wrapper);
        return orders;
    }

    @Override
    public OrderDetailVO getById(Long id) {
        Order order = orderMapper.selectById(id);
        if (!order.getUserId().equals(BaseContext.getCurrentId())){
            throw new PowerException(ErrorConstant.INSUFFICIENT_PRIVILEGES);
        }
        QueryWrapper<OrderDetail> wrapper=new QueryWrapper<OrderDetail>()
                .eq("order_id",id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper);
        AddressBook addressBook = addressBookMapper.selectById(order.getAddressId());
        OrderDetailVO orderDetailVO=new OrderDetailVO();
        orderDetailVO.setOrderNumber(order.getOrderNumber());
        orderDetailVO.setOrderStatus(order.getStatus());
        orderDetailVO.setTotalPrice(order.getPrice());
        orderDetailVO.setGoods(orderDetails);
        orderDetailVO.setAddressBook(addressBook);
        return orderDetailVO;
    }

    @Override
    public void chargebacks(Long id) {
        Order order = orderMapper.selectById(id);
        if (!order.getUserId().equals(BaseContext.getCurrentId())){
            throw new PowerException(ErrorConstant.INSUFFICIENT_PRIVILEGES);
        }
        if (!order.getStatus().equals(Order.WAIT_GIVE)){
            throw new OrderException(ErrorConstant.CAN_NOT_CHARGEBACKS);
        }
        order.setStatus(Order.CANCEL);
        orderMapper.updateById(order);
    }
}
